from django.contrib.auth.models import Permission, Group
from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer

from apps.goods.models import SKUImage, SKU
from apps.users.models import User


class MyJSONWebTokenSerializer(JSONWebTokenSerializer):

    def validate(self, attrs):
        # 1. 调用父类的validate方法判断是不是合法，如果不合法就直接抛出错误了
        # 2. 自己判断用户是不是管理员，如果时管理员才可以正常登录，否则就抛出权限验证失败的异常
        ret = super(MyJSONWebTokenSerializer, self).validate(attrs)
        user = ret.get('user')
        if not user.is_staff:
            raise serializers.ValidationError('非管理员不能登录管理后台')
        return ret

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)


class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'


class GroupSerializer(serializers.ModelSerializer):
    permissions = serializers.PrimaryKeyRelatedField(many=True, queryset=Permission.objects.all())

    class Meta:
        model = Group
        fields = '__all__'


# 管理员管理的序列化器
class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ('password', )

    def create(self, validated_data):
        user = super(AdminSerializer, self).create(validated_data)
        user.is_staff = True
        user.set_password(self.data.get('password'))
        user.save()
        return user

# 图片的序列化器
class ImageSerializer(serializers.ModelSerializer):
    # sku = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        fields = '__all__'



class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model=SKU
        fields='__all__'

